package com.greenant.store.view;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.greenant.store.AntHomeApplication;
import com.greenant.store.R;
import com.greenant.store.activity.CaptureActivity;
import com.greenant.store.activity.ExpressManageActivity;
import com.greenant.store.bean.EMRecv;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.utils.UtilTools;
import com.greenant.store.utils.iLog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ExpressTabView1 extends RelativeLayout {

	private Context mContext;
	private ListView listView;

	private List<EMRecv> orderItemList = new ArrayList<EMRecv>();
	EMRecvListAdapter emrecvListAdapter;
	private Button makeSend;
	
	private EditText emrecvidTemp;
	private EditText phoneTemp;
	
	private RelativeLayout dataView;
	private RelativeLayout progressView;
	

	public ExpressTabView1(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	public ExpressTabView1(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}

	public ExpressTabView1(Context context) {
		super(context);
		mContext = context;
		init();
	}

	private void init() {
		View view = LayoutInflater.from(mContext).inflate(R.layout.view_express_tab1, this);
		listView = (ListView) view.findViewById(R.id.orderlist);
//		EMRecv emrecv=new EMRecv();
//		orderItemList.add(emrecv);
		EMRecv emrecv1=new EMRecv();
		orderItemList.add(emrecv1);
		emrecvListAdapter=new EMRecvListAdapter(orderItemList, mContext);
		listView.setAdapter(emrecvListAdapter);
		makeSend=(Button)findViewById(R.id.makeSend);
		dataView=(RelativeLayout)findViewById(R.id.dataView);
		progressView=(RelativeLayout)findViewById(R.id.progressView);
		makeSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isAllDataValid(orderItemList))

				{
					dataView.setVisibility(View.GONE);
					progressView.setVisibility(View.VISIBLE);
					RetrieveDataAsyn.getInstance().makeEmrecv(orderItemList, 0, new RetrieveDataListener() {

						@Override
						public void dataRetrieved(int requestId, Object data) {
							if (data == null) {
								UtilTools.showMyToast(mContext, mContext.getString(R.string.failed));
							} else {
								UtilTools.showMyToast(mContext, mContext.getString(R.string.success));
							}
							 orderItemList.clear();
                             EMRecv emrecv2 = new EMRecv();
                             orderItemList.add(emrecv2);
                             emrecvListAdapter.notifyDataSetChanged();
							
							dataView.setVisibility(View.VISIBLE );
							progressView.setVisibility(View.GONE);
						}
					});
				} else {
					UtilTools.showMyToast(mContext, mContext.getString(R.string.emrecv_send_company_hint1));
				}
			}
		});
	}

	class EMRecvListAdapter extends BaseAdapter {

		private List<EMRecv> list;
		private Context context;
		// BitmapUtils bitmapUtils;
		private final static String TAG = "MyEmrecvListAdapter";

		String cash_on_delivery = "";
		DecimalFormat df = new DecimalFormat("#########.##");

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}

		public EMRecvListAdapter(List<EMRecv> tlist, Context ctx) {
			this.list = tlist;
			this.context = ctx;
			cash_on_delivery = context.getString(R.string.order_ensure_pay_method_cash_on_delivery);
			
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			ViewHolder viewHolder = null;
//			if (convertView == null) {
				LayoutInflater inflater = ((Activity) context).getLayoutInflater();
				convertView = inflater.inflate(R.layout.item_emrecv_send, null);
				viewHolder = new ViewHolder();

				viewHolder.emrecvname = (TextView) convertView.findViewById(R.id.emrecvname);
				viewHolder.emrecvid = (EditText) convertView.findViewById(R.id.emrecvid);
				viewHolder.emrecvidscan = (ImageView) convertView.findViewById(R.id.emrecvidscan);
				viewHolder.emrecvphone = (EditText) convertView.findViewById(R.id.emrecvphone);
				viewHolder.emrecvtitle = (RelativeLayout) convertView.findViewById(R.id.emrecvtitle);
				
				convertView.setTag(viewHolder);

//			} else {
//				viewHolder = (ViewHolder) convertView.getTag();
//			}
			
			final ViewHolder viewHolderTemp = viewHolder;
			final EMRecv order = list.get(position);

			viewHolder.emrecvid.setText(order.getEMId());
			viewHolder.emrecvphone.setText(order.getReceiverPhone()); 
			if(order.getEMCompany()!=null)
			{
				viewHolder.emrecvname.setText(order.getEMCompany().getCompanyName());
			}else{
				viewHolder.emrecvname.setText("");	
			}
			
			
			viewHolderTemp.TAG=order.getTag();
			
			viewHolder.emrecvidscan.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					emrecvidTemp=viewHolderTemp.emrecvid;
					phoneTemp=viewHolderTemp.emrecvphone;
					Activity activity=(Activity)mContext;
					Intent intent=new Intent(mContext,CaptureActivity.class);
					intent.putExtra(CaptureActivity.KEY_CAPTURE_TYPE, CaptureActivity.CAPTURE_TYPE_EMRECV);
					intent.putExtra(ExpressManageActivity.REQUEST_KEY_POSITION, position);
					activity.startActivityForResult(intent, ExpressManageActivity.REQUESTCODE_TYPE_1);
				}
			});
			
			
			final View parentT=viewHolder.emrecvname;
			
			
			viewHolder.emrecvtitle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(AntHomeApplication.emcompanyInfos.isEmpty())
					{
						UtilTools.showMyToast(mContext, mContext.getString(R.string.emrecv_send_company_hint));
					}
					else{
						Iterator<String> itr = AntHomeApplication.emcompanyInfos.keySet().iterator();
						final String[] items=new String[AntHomeApplication.emcompanyInfos.size()];
						int i=0;
						while(itr.hasNext())
						{
							items[i]=itr.next();
							i++;
						}
						
						final PopMenu popMenu = new PopMenu(mContext);
						
						popMenu.addItems(items, null);
						popMenu.showAsDropDown(parentT);
						popMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
								popMenu.dismiss();
//								if(!TextUtils.isEmpty(viewHolderTemp.TAG)&&viewHolderTemp.TAG.equals(order.getTag()))
//								{
									order.setEMCompany(AntHomeApplication.emcompanyInfos.get(items[arg2]));
									viewHolderTemp.emrecvname.setText(AntHomeApplication.emcompanyInfos.get(items[arg2]).getCompanyName());
//									notifyDataSetChanged();
//								}
								
								
							}
						});
					}
					
				}
			});
			
			
			viewHolder.emrecvid.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					if (s != null) {
						if (!TextUtils.isEmpty(order.getTag()) && order.getTag().equals(viewHolderTemp.TAG)) {
							order.setEMId(s.toString());
							addNewItem();
						}

					}
					
				}
			});
			
			viewHolder.emrecvphone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)}); //最大输入长度  
			viewHolder.emrecvphone.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
					
				}
				
				@Override
				public void afterTextChanged(Editable s) {
					if (!TextUtils.isEmpty(order.getTag()) && order.getTag().equals(viewHolderTemp.TAG)) {
						if (s != null) {
							try {

								String sss = s.toString();
								if (!TextUtils.isEmpty(sss) && sss.length() == 11 && TextUtils.isDigitsOnly(sss)) {
									order.setReceiverPhone(sss);
									addNewItem();

								}
								iLog.d("mapString:" + position + " " + s.toString());
								

							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
				
			});

			return convertView;
		}

		class ViewHolder {
			public TextView emrecvname;
			public EditText emrecvid;
			public ImageView emrecvidscan;
			public EditText emrecvphone;
			public RelativeLayout	emrecvtitle;
			public String TAG=null;
		}

	}
	
	private void addNewItem(){
		
		if (isAllDataSet(orderItemList)) {
			EMRecv emrecv = new EMRecv();
			orderItemList.add(emrecv);
			if (emrecvListAdapter != null) {
				emrecvListAdapter.notifyDataSetChanged();
			}
			invalidate();
			
			listView.postDelayed(new Runnable() {

				@Override
				public void run() {
					final View v = listView.getChildAt(orderItemList.size() - 1 - listView.getFirstVisiblePosition());
					if (v != null) {

						View v2 = v.findViewById(R.id.emrecvphone);
						if (v2 != null) {
							v2.performClick();
							v2.requestFocus();

							iLog.d("v2.requestFocus:");
						}
						listView.postDelayed(new Runnable() {

							@Override
							public void run() {
								View v1 = v.findViewById(R.id.emrecvid);
								if (v1 != null) {
									v1.performClick();
									v1.requestFocus();

									iLog.d("v1.requestFocus:");
								}
							}
						}, 100);

					}
				}
			}, 200);
			
			for(int i=0;i<orderItemList.size();i++)
			{
				iLog.d("addNewItem:"+orderItemList.get(i).getEMId()+" phone:"+orderItemList.get(i).getReceiverPhone());
			}
			
		}
	}
	
	public void modifyPositonData(int position, String erCode) {

		if (position < orderItemList.size()) {
			EMRecv temp = orderItemList.get(position);
			temp.setEMId(erCode);
			if (isAllDataSet(orderItemList)) {
				addNewItem();
			} else {
				if (emrecvListAdapter != null) {
					emrecvListAdapter.notifyDataSetChanged();
				}
				if (temp.isPhoneSet()) {
					if (emrecvidTemp != null)
						emrecvidTemp.performClick();
				} else {
					if (phoneTemp != null)
						phoneTemp.performClick();
				}

			}
			
		}

	}
	
	private boolean isAllDataSet(List<EMRecv> orderItemList ){
	    
	    if(orderItemList!=null&&orderItemList.size()>0)
	    {
	        for(int i=0;i<orderItemList.size();i++)
	        {
	            if(!orderItemList.get(i).isSet())
	            {
	             return false;   
	            }
	        }
	    }
	    return true;
	}
	
	private boolean isAllDataValid(List<EMRecv> orderItemList) {

		if (orderItemList != null && orderItemList.size() > 1) {
			for (int i = 0; i < orderItemList.size()-1; i++) {
				if (!orderItemList.get(i).isSet() || orderItemList.get(i).getEMCompany() == null) {
					return false;
				}
			}
		}
		return true;
	}

}
